<template>
  <div ref="editorElem"></div>
</template>

<script>
import wangeditor from 'wangeditor'
import menus from './menus'

export default {
  name: 'WangEditor',

  props: {
    value: {
      type: String,
      default: null
    },

    disable: {
      type: Boolean,
      default: false
    }
  },

  data: () => ({
    hasChange: false,
    hasInit: false,
    editor: null
  }),

  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() => this.setEditorData(val))
      }
    }
  },

  mounted() {
    this.init()
  },

  beforeDestroy() {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.editor.destroy()
    window.onbeforeunload = () => {}
    this.editor = null
  },

  methods: {
    init() {
      const editor = new wangeditor(this.$refs.editorElem)

      editor.config.onchangeTimeout = 500

      editor.config.menus = menus

      // 配置 onchange 回调函数，将数据同步到 vue 中
      editor.config.onchange = (newHtml) => {
        this.hasChange = true
        this.$emit('input', newHtml)
      }

      // 创建编辑器
      editor.create()

      if (this.disable) editor.disable()

      if (this.value) {
        editor.txt.html(this.value)
      }

      this.editor = editor

      this.hasInit = true

      window.onbeforeunload = () => '你所做的更改可能未保存。'
    },

    setEditorData(value) {
      this.editor.txt.html(value)
    },

    getEditorData() {
      // 通过代码获取编辑器内容
      let data = this.editor.txt.html()
      alert(data)
    }
  }
}
</script>
